package com.live.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.live.common.Constant;
import com.live.common.LiveImageHelper;
import com.live.task.LiveDetail;
import com.live.task.LiveFavor;
import com.live.task.LiveMemberStats;
import com.live.task.LiveReview;
import com.live.task.LiveScore;
import com.live.task.LiveTeamStats;
import com.live.task.LiveVideo;
import com.live.tools.LiveTools;

public class LiveDetailActivity extends LiveBaseActivity {

	private Bundle bundle;

	private LiveImageHelper image;

	protected static final int UPDATE_TEXT = 0;

	private LiveReview reviewTask = null;
	private LiveTeamStats teamStatsTask = null;
	private LiveMemberStats memberStatsTask = null;
	private LiveFavor favorTask = null;

	public boolean refresh = true;

	private Timer mTimer;
	private TimerTask mTimerTask;
	private Handler mHandler;

	private TextView matchName = null;
	private TextView homeTeam = null;
	private TextView homeTeamScore = null;
	private ImageView homeTeamPic = null;
	private TextView homeFavor = null;
	private TextView visitTeam = null;
	private TextView visitTeamScore = null;
	private ImageView visitTeamPic = null;
	private TextView visitFavor = null;
	private TextView matchStatus = null;
	private TextView matchEventStatus = null;
	private String matchCategory = null;
	private String matchRecord = null;
	private String visitTeamName = null;
	private String homeTeamName = null;

	private Dialog favorDialog = null;

	private LinearLayout viewMatch = null;
	private ListView viewMatchLive = null;
	private TextView viewMatchLiveMsg = null;
	// private TextView viewMatchLiveWaitMsg = null;
	private RelativeLayout viewTeamStatsBbs = null;
	private ScrollView viewTeamStstsB = null;
	private ScrollView viewTeamStstsF = null;
	private TextView viewTeamStstsMsg = null;
	private ScrollView viewMemberStatsB = null;
	private ScrollView viewMemberStatsF = null;
	private TextView viewMemberStatsMsg = null;
	private ListView viewMatchVideo = null;
	private TextView viewMatchVideoMsg = null;

	private LinearLayout loadData = null;

	private ListView reviewList = null;

	public int setTimeout = 60000;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 网络连接判断
		if (netIsOk) {

			setContentView(R.layout.live_detail);

			/* 获取Intent中的Bundle对象 */
			bundle = this.getIntent().getExtras();

			/* 获取Bundle中的数据，注意类型和key */
			homeTeam = (TextView) findViewById(R.id.homeTeam);
			homeTeamScore = (TextView) findViewById(R.id.homeTeamScore);
			homeTeamPic = (ImageView) findViewById(R.id.homeTeamPic);

			homeFavor = (TextView) findViewById(R.id.homeFavor);
			visitTeam = (TextView) findViewById(R.id.visitTeam);
			visitTeamScore = (TextView) findViewById(R.id.visitTeamScore);
			visitTeamPic = (ImageView) findViewById(R.id.visitTeamPic);

			visitFavor = (TextView) findViewById(R.id.visitFavor);
			matchStatus = (TextView) findViewById(R.id.matchStatus);
			matchStatus.setText(bundle.getString("matchStatus"));

			matchEventStatus = (TextView) findViewById(R.id.matchEventStatus);
			matchEventStatus.setText(bundle.getString("matchStatus"));

			matchName = (TextView) findViewById(R.id.matchName);
			matchName.setText(bundle.getString("matchName"));

			homeTeam.setText(bundle.getString("homeTeam"));
			homeTeamScore.setText(bundle.getString("homeTeamScore"));

			image = new LiveImageHelper(homeTeamPic);
			image.execute(bundle.getString("homeTeamPic"));

			visitTeam.setText(bundle.getString("visitTeam"));
			visitTeamScore.setText(bundle.getString("visitTeamScore"));

			image = new LiveImageHelper(visitTeamPic);
			image.execute(bundle.getString("visitTeamPic"));

			matchCategory = bundle.getString("matchCategory");
			matchRecord = bundle.getString("matchRecord");

			// 设置球队名称，为粉丝支持提供KEY
			homeTeamName = bundle.getString("homeTeamName");
			visitTeamName = bundle.getString("visitTeamName");

			homeFavor.setText("0");
			visitFavor.setText("0");
			TextView favor = (TextView) findViewById(R.id.favor);
			favor.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					favorDialog = new Dialog(context, R.style.dialog);
					// 去掉标题
					favorDialog.setContentView(R.layout.live_favor);
					favorDialog.setCanceledOnTouchOutside(true);
					// 为获取屏幕宽、高
					Display d = getWindowManager().getDefaultDisplay();
					// 获取对话框当前的参数值
					LayoutParams p = favorDialog.getWindow().getAttributes();
					// 宽度设置
					p.width = (int) (d.getWidth() * 0.95);
					// 设置生效
					favorDialog.getWindow().setAttributes(p);
					// 显示对话框
					favorDialog.show();

					ImageView homeTeamPic = (ImageView) favorDialog.findViewById(R.id.homeTeamPic);
					ImageView visitTeamPic = (ImageView) favorDialog.findViewById(R.id.visitTeamPic);

					TextView favorHomeTeam = (TextView) favorDialog.findViewById(R.id.homeTeam);
					favorHomeTeam.setText(bundle.getString("homeTeam"));
					TextView favorVisitTeam = (TextView) favorDialog.findViewById(R.id.visitTeam);
					favorVisitTeam.setText(bundle.getString("visitTeam"));

					// 设置球队头像
					image = new LiveImageHelper(homeTeamPic);
					image.execute(bundle.getString("homeTeamPic"));
					image = new LiveImageHelper(visitTeamPic);
					image.execute(bundle.getString("visitTeamPic"));

					homeTeamPic.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							favorTask = new LiveFavor(context, homeTeamName, homeFavor, visitFavor);
							favorTask.execute(bundle);
							favorDialog.dismiss();
						}
					});

					visitTeamPic.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							favorTask = new LiveFavor(context, visitTeamName, homeFavor, visitFavor);
							favorTask.execute(bundle);
							favorDialog.dismiss();
						}
					});
				}
			});

			// 设置刷新时间
			if (matchCategory.equals("1")) {
				// 篮球
				setTimeout = 10000;
			} else if (matchCategory.equals("2") || matchCategory.equals("3")) {
				// 足球
				setTimeout = 15000;
			} else if (matchCategory.equals("6")) {
				// 网球
				setTimeout = 15000;
			} else {
				// 其他
				setTimeout = 15000;
			}

			LinearLayout viewMatchInfo = (LinearLayout) findViewById(R.id.view_match_info);
			LinearLayout viewMatchEventInfo = (LinearLayout) findViewById(R.id.view_match_event_info);
			LinearLayout viewMatchHomeInfo = (LinearLayout) findViewById(R.id.view_match_home_info);
			LinearLayout viewMatchScoreInfo = (LinearLayout) findViewById(R.id.view_match_score_info);
			LinearLayout viewMatchVisitInfo = (LinearLayout) findViewById(R.id.view_match_visit_info);

			viewMatchInfo.removeAllViews();
			if ("".equals(homeTeam.getText()) && "".equals(visitTeam.getText())) {
				viewMatchInfo.addView(viewMatchEventInfo);
			} else {
				viewMatchInfo.addView(viewMatchHomeInfo);
				viewMatchInfo.addView(viewMatchScoreInfo);
				viewMatchInfo.addView(viewMatchVisitInfo);
			}

			viewMatch = (LinearLayout) findViewById(R.id.view_match);
			viewMatchLive = (ListView) findViewById(R.id.view_match_live);
			viewMatchLiveMsg = (TextView) findViewById(R.id.view_match_live_msg);
			// viewMatchLiveWaitMsg = (TextView)
			// findViewById(R.id.view_match_live_wait_msg);
			viewTeamStatsBbs = (RelativeLayout) findViewById(R.id.view_match_bbs);
			viewTeamStstsB = (ScrollView) findViewById(R.id.view_team_stats_b);
			viewTeamStstsF = (ScrollView) findViewById(R.id.view_team_stats_f);
			viewTeamStstsMsg = (TextView) findViewById(R.id.view_team_stats_msg);
			viewMemberStatsB = (ScrollView) findViewById(R.id.view_member_stats_b);
			viewMemberStatsF = (ScrollView) findViewById(R.id.view_member_stats_f);
			viewMemberStatsMsg = (TextView) findViewById(R.id.view_member_stats_msg);
			viewMatchVideo = (ListView) findViewById(R.id.view_match_video);
			viewMatchVideoMsg = (TextView) findViewById(R.id.view_match_video_msg);
			loadData = (LinearLayout) findViewById(R.id.loadData);
			viewMatch.removeAllViews();

			// 初始化“直播”TAG
			if (matchRecord != null) {
				viewMatch.addView(viewMatchLive);
			} else {
				viewMatch.addView(viewMatchLiveMsg);
			}

			// 文字直播
			TextView matchLive = (TextView) findViewById(R.id.matchLive);
			matchLive.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					changeTabInit();

					TextView matchLiveLine = (TextView) findViewById(R.id.matchLiveLine);
					matchLiveLine.setVisibility(Constant.VISIBLE);

					if (matchRecord != null) {
						viewMatch.addView(viewMatchLive);
					} else {
						viewMatch.addView(viewMatchLiveMsg);
					}
				}
			});

			// 粉丝交流
			TextView matchBbs = (TextView) findViewById(R.id.matchBbs);
			matchBbs.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					changeTabInit();

					TextView matchBbsLine = (TextView) findViewById(R.id.matchBbsLine);
					matchBbsLine.setVisibility(Constant.VISIBLE);

					viewMatch.addView(loadData);
					viewMatch.addView(viewTeamStatsBbs);

					reviewList = (ListView) findViewById(R.id.reviewList);

					bundle.putString("type", "select");
					reviewTask = new LiveReview(context, reviewList, viewMatch);
					reviewTask.execute(bundle);

					// 发表评论按钮
					Button sendMsgBtn = (Button) findViewById(R.id.sendMsgBtn);
					sendMsgBtn.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {

							// 如果用户已经登录，则可以发表评论
							if (userStatus == Constant.LOGIN) {

								EditText reviewText = (EditText) findViewById(R.id.reviewText);
								if (reviewText.getText().length() != 0) {
									String url = Constant.SITE_URL + "live_review_add.php?locale="
											+ LiveTools.getLocaleLanguage() + "&";
									url += "matchId=" + bundle.getString("matchId");

									String userId = store.getString("userId", null);
									String userReview = reviewText.getText().toString();
									List<NameValuePair> params = new ArrayList<NameValuePair>();
									params.add(new BasicNameValuePair("reviewUser", userId));
									params.add(new BasicNameValuePair("reviewText", userReview));

									// 添加评论
									if (reviewTask.addMatchReview(url, params)) {

										// 刷新评论列表
										LiveReview task = new LiveReview(context, reviewList, loadData);
										task.execute(bundle);

										// 清空输入框
										reviewText.setText("");

										// 关闭输入法键盘
										InputMethodManager m = (InputMethodManager) context
												.getSystemService(Context.INPUT_METHOD_SERVICE);
										m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

									}
								}
							} else {
								// 如果用户没有登录，则跳转到登录页
								Intent intent = new Intent();
								intent.setClass(context, LiveUserLoginActivity.class);
								context.startActivity(intent);
							}
						}
					});
				}
			});

			// 球队统计
			TextView matchTeamStats = (TextView) findViewById(R.id.matchTeamStats);
			matchTeamStats.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					changeTabInit();

					TextView matchTeamStatsLine = (TextView) findViewById(R.id.matchTeamStatsLine);
					matchTeamStatsLine.setVisibility(Constant.VISIBLE);

					// 只有篮球、足球比赛才有球队统计
					if ((Integer.parseInt(matchCategory) == 1 || Integer.parseInt(matchCategory) == 2 || Integer
							.parseInt(matchCategory) == 3)
							&& matchRecord != null
							&& !"".equals(homeTeam.getText())
							&& !"".equals(visitTeam.getText())) {

						viewMatch.addView(loadData);

						if ("1".equals(matchCategory)) {
							viewMatch.addView(viewTeamStstsB);
							teamStatsTask = new LiveTeamStats(viewTeamStstsB, viewMatch);
						} else if ("2".equals(matchCategory) || "3".equals(matchCategory)) {
							viewMatch.addView(viewTeamStstsF);
							teamStatsTask = new LiveTeamStats(viewTeamStstsF, viewMatch);
						}

						teamStatsTask.execute(bundle);
					} else {
						viewMatch.addView(viewTeamStstsMsg);
					}
				}
			});

			// 球员统计
			TextView matchMemberStats = (TextView) findViewById(R.id.matchMemberStats);
			matchMemberStats.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {

					changeTabInit();

					TextView matchMemberStatsLine = (TextView) findViewById(R.id.matchMemberStatsLine);
					matchMemberStatsLine.setVisibility(Constant.VISIBLE);

					// 只有篮球、足球比赛才有球员统计
					if ((Integer.parseInt(matchCategory) == 1 || Integer.parseInt(matchCategory) == 2 || Integer
							.parseInt(matchCategory) == 3)
							&& matchRecord != null
							&& !"".equals(homeTeam.getText())
							&& !"".equals(visitTeam.getText())) {

						viewMatch.addView(loadData);

						if ("1".equals(matchCategory)) {
							viewMatch.addView(viewMemberStatsB);
							memberStatsTask = new LiveMemberStats(context, viewMatch);
						} else if ("2".equals(matchCategory) || "3".equals(matchCategory)) {
							viewMatch.addView(viewMemberStatsF);
							memberStatsTask = new LiveMemberStats(context, viewMatch);
						}

						memberStatsTask.execute(bundle);
					} else {
						viewMatch.addView(viewMemberStatsMsg);
					}
				}
			});

			// 精彩视频
			TextView matchVideo = (TextView) findViewById(R.id.matchVideo);
			matchVideo.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					changeTabInit();

					TextView matchVideoLine = (TextView) findViewById(R.id.matchVideoLine);
					matchVideoLine.setVisibility(Constant.VISIBLE);

					// 暂且只提供NBA比赛的精彩视频
					if (bundle.getString("matchName").indexOf("NBA") >= 0) {
						viewMatch.addView(loadData);
						viewMatch.addView(viewMatchVideo);
						// 取得视频数据
						LiveVideo task = new LiveVideo(context, viewMatchVideo, viewMatch);
						task.execute(bundle);
					} else {
						viewMatch.addView(viewMatchVideoMsg);
					}
				}
			});

			// 判断是否提供文字直播
			if (matchRecord != null) {

				// 取得比分数据
				if (!Constant.MATCH_STATUS_1.equals(bundle.getString("matchStatus"))) {
					LiveScore task = new LiveScore(context, viewMatchLive, homeTeamScore, visitTeamScore, matchStatus,
							true);
					task.execute(bundle);
				}else{
					Toast.makeText(context, R.string.live_text_wait, Toast.LENGTH_LONG).show();
				}

				// 定时刷新比分数据
				if (!Constant.MATCH_STATUS_4.equals(bundle.getString("matchStatus"))) {
					mHandler = new Handler() {
						@Override
						public void handleMessage(Message msg) {
							switch (msg.what) {
							case UPDATE_TEXT:
								LiveScore task = new LiveScore(context, viewMatchLive, homeTeamScore, visitTeamScore,
										matchStatus, false);
								task.execute(bundle);
								break;
							}
						}
					};

					mTimerTask = new TimerTask() {

						@Override
						public void run() {
							Log.d("AndroidTimerDemo", "timer");
							mHandler.sendEmptyMessage(UPDATE_TEXT);
						}
					};

					mTimer = new Timer();
					mTimer.schedule(mTimerTask, setTimeout, setTimeout); // 延时10000ms后执行，10000ms执行一次
				}
			}

			// 取得支持数据
			favorTask = new LiveFavor(context, null, homeFavor, visitFavor);
			favorTask.execute(bundle);

			// 记录进出比赛详细页的信息
			LiveDetail detailTask = new LiveDetail(context, Constant.INPUT);
			detailTask.execute(bundle);
		}
	}

	private void changeTabInit() {
		// 隐藏下划线
		TextView matchLiveLine = (TextView) findViewById(R.id.matchLiveLine);
		matchLiveLine.setVisibility(Constant.INVISIBLE);
		TextView matchBbsLine = (TextView) findViewById(R.id.matchBbsLine);
		matchBbsLine.setVisibility(Constant.INVISIBLE);
		TextView matchTeamStatsLine = (TextView) findViewById(R.id.matchTeamStatsLine);
		matchTeamStatsLine.setVisibility(Constant.INVISIBLE);
		TextView matchMemberStatsLine = (TextView) findViewById(R.id.matchMemberStatsLine);
		matchMemberStatsLine.setVisibility(Constant.INVISIBLE);
		TextView matchVideoLine = (TextView) findViewById(R.id.matchVideoLine);
		matchVideoLine.setVisibility(Constant.INVISIBLE);

		viewMatch.removeAllViews();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (mTimer != null) {
				mTimer.cancel();
			}

			// 记录退出比赛详细页的信息
			LiveDetail detailTask = new LiveDetail(context, Constant.OUTPUT);
			detailTask.execute(bundle);

			return super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}
}